package cn._2dland.bots.jdo;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import cn._2dland.bots.jdo.models.U115Account;

public class U115AccountManager {
	private U115AccountManager() {}

	/**
	 * 创建账户
	 * @param username - 用户名
	 * @param password - 密码
	 * @return 创建后的账户
	 */
	public static U115Account create(String username, String password){
		U115Account acct = new U115Account(username, password);

		PersistenceManager pm = PMFactory.getPMFInstance().getPersistenceManager();
		Transaction trans = pm.currentTransaction();
		try {
			trans.begin();
			pm.makePersistent(acct);
			trans.commit();
		}
		catch (Exception e) {
			acct = null;
			e.printStackTrace();
		}
		finally {
			if(trans.isActive())
				trans.rollback();
			if(pm != null)
				pm.close();
		}
		return acct;
	}

	/**
	 * 删除账户
	 * @param id - 账户ID
	 * @return
	 */
	public static boolean remove(Long id) {
		boolean bOK = false;
		PersistenceManager pm = PMFactory.getPMFInstance().getPersistenceManager();
		Transaction trans = pm.currentTransaction();
		try {
			U115Account acct = pm.getObjectById(U115Account.class, id);
			trans.begin();
			pm.deletePersistent(acct);
			trans.commit();

			bOK = true;
		}
		catch (Exception e) {
			bOK = false;
			e.printStackTrace();
		}
		finally {
			if(trans.isActive())
				trans.rollback();
			if(pm != null)
				pm.close();
		}
		return bOK;
	}

	/** 设置账户状态 */
	public static boolean setStatus(Long id, int status) {
		boolean bOK = false;
		PersistenceManager pm = PMFactory.getPMFInstance().getPersistenceManager();
		Transaction trans = pm.currentTransaction();
		try {
			U115Account acct = pm.getObjectById(U115Account.class, id);
			trans.begin();
			acct.setStatus(status);
			trans.commit();

			bOK = true;
		}
		catch (Exception e) {
			bOK = false;
			e.printStackTrace();
		}
		finally {
			if(trans.isActive())
				trans.rollback();
			if(pm != null)
				pm.close();
		}
		return bOK;
	}
}